package top.ewind.controller.admin.device;

import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;

import top.ewind.controller.common.AdminRootCtrl;
import top.ewind.model.SysDictory;
import top.ewind.util.DateUtil;
import top.ewind.util.SecurityUtil;

public class TestCtrl extends AdminRootCtrl {
	private static IMqttClient client = null;
	private static Logger LOG = LoggerFactory.getLogger(TestCtrl.class);
	
	public void index() {
		render("index.html");
	}

	public void user() {
		setAttr("mqttserver",SysDictory.getConfig("mqttserver"));
		render("user.html");
	}
	
	@Clear
	public void revice(){
		System.out.println("revice--------"+HttpKit.readData(getRequest()));
		renderNull();
	}
	public void connectuser(){
		String[] clientid = getPara("cid").split("/");
		Long timestamp = System.currentTimeMillis();
		String userkey = Db.queryStr("select t.userkey from device_user t where t.id = ?",clientid[1]);
		String password = SecurityUtil.md5(userkey+timestamp)+","+timestamp;
		System.out.println("clientId:"+getPara("cid"));
		System.out.println("userkey:"+userkey);
		System.out.println("username:"+clientid[1]);
		System.out.println("password"+password);
		renderJson("msg",password);
	}
	public void connect(){
		LOG.debug("++++++++++++++++++++++++++设备连接++++++++++++++++++++++++++++++");
		try {
			MqttConnectOptions options = new MqttConnectOptions();
			String[] clientid = getPara("cid").split("/");
			options.setUserName(clientid[1]);
			LOG.debug("++++++++++++++++++++++++++"+clientid[1]+"++++++++++++++++++++++++++++++");
			String pid = Db.queryStr("select t.pid from device t where t.id = ?",clientid[1]);
			String pmkey = Db.queryStr("select t.pmkey from device_product t where t.id = ?",pid);
			Long timestamp = System.currentTimeMillis();
			String password = SecurityUtil.md5(pmkey+timestamp)+","+timestamp;
			LOG.debug(pid+pmkey+password+clientid[1]);
			options.setPassword(password.toCharArray());
			client = new MqttClient("tcp://"+SysDictory.getConfig("mqttserver")+":1880", getPara("cid"));
			MessageListener listener = new MessageListener();
	     	client.setCallback(listener);
			client.connect(options);
			client.subscribe("in/"+pid+"/"+clientid[1]);
			renderJson("msg","success");
		} catch (MqttException e) {
			e.printStackTrace();
			renderJson("msg","出错了");
		}
	}
    
	public void disconnect(){
		LOG.debug("++++++++++++++++++++++++++断开连接++++++++++++++++++++++++++++++");
		try {
			client.disconnect();
			renderJson("msg","success");
		} catch (MqttException e) {
			renderJson("msg","出错了");
		}
	}

	public void publish(){		
		try {
			String[] clientid = getPara("cid").split("/");
			String pid = Db.queryStr("select t.pid from device t where t.id = ?",clientid[1]);
			MqttTopic topic = client.getTopic("out/"+pid+"/"+clientid[1]);
		    MqttMessage message = new MqttMessage(getPara("para").getBytes());
			topic.publish(message);
			renderJson("msg","success");
		} catch (MqttException e) {
			renderJson("msg","出错了");
		}
	}
	class MessageListener implements MqttCallback {

		@Override
		public void connectionLost(Throwable paramThrowable) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void messageArrived(String paramString, MqttMessage paramMqttMessage) throws Exception {
			LOG.error("reciveMsg from "+paramString+" Date:"+DateUtil.now()+" Content:"+paramMqttMessage.toString());
		}

		@Override
		public void deliveryComplete(IMqttDeliveryToken paramIMqttDeliveryToken) {
			// TODO Auto-generated method stub
			
		}
		
	}

}